<template>
  <div class="login">
    <a-card class="login-card" title="账号登录">
      <a-form ref="formRef" class="login-form" :model="loginForm" :rules="rules">
        <a-form-item name="user_name">
          <a-input v-model:value.trim="loginForm.user_name" size="large" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item name="password">
          <a-input-password
            size="large"
            v-model:value="loginForm.password"
            autocomplete="on"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
          />
        </a-form-item>
        <a-form-item>
          <a-button class="submit" size="large" type="primary" @click="onLogin">登录</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>
<script setup lang="ts">
  import { message } from 'ant-design-vue';
  import { onMounted, onUnmounted, reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  /* 引入规则校验工具类，使用其中的 getRequiredRules 方法 */
  import { Rules, LocalStorage } from '@/utils/utils';
  /* 引入 store(pinia) 用户信息模块，用于保存用户登录后的信息,用户信息类型、菜单类型 */
  import { UserInfoStore, type UserInfo, type MenuItem } from '@/store/modules/user-info';
  import { LoadingStore } from '@/store/modules/loading'; //导入全局 loading 模块

  import { loginApi } from '@/api/login'; //引入登录接口
  import { buildRoutes } from '@/router'; //引入动态路由构建函数函数

  /* 表单校验规则 */
  const rules = {
    loginName: Rules.getRequiredRules('用户名不能为空'),
    password: Rules.getRequiredRules('密码不能为空'),
  };

  /* 表单元素对象 */
  const loginForm = reactive({
    user_name: 'root',
    password: '123456',
  });

  /* 密码可见 */
  const showPassword = ref(false);
  /* 定义表达对象，配合rules 进行表单校验使用 */
  const formRef = ref();

  /* 监听键盘事件,回车 登录 */
  onMounted(() => {
    document.onkeyup = (e) => {
      if (e.keyCode === 13) {
        onLogin();
      }
    };
  });

  /* 注销键盘事件 */
  onUnmounted(() => {
    document.onkeyup = null;
  });

  const loading = LoadingStore(); //实例化全局 loading 模块
  const userInfoStore = UserInfoStore(); //实例化全局用户信息模块
  const router = useRouter(); //引入路由实例
  /* 异步操作访问接口 */
  async function onLogin() {
    try {
      await formRef.value.validate();
      loading.show();
      const result: UserInfo = await loginApi.login(loginForm);
      message.success('登录成功');

      LocalStorage.set('token', result.token); //将 token 写入到本地存储中
      LocalStorage.set('loginName', 'AdminLogin'); //保存总管理后台登录页路径
      LocalStorage.set('userInfo', JSON.stringify(result)); //将用户信息写入到本地存储中，用于刷新时重载 pinia 中的用户信息
      userInfoStore.setUserInfo(result); //将用户信息写入到 pinia 中

      await buildRoutes(result.menu_list as MenuItem[]); // 等待路由构建完成

      router.push('/home'); //路由构建完成，调转到首页
    } catch (error) {
      Promise.reject(error); //未中断程序执行，只向错误处理程序传递错误
    }
    loading.hide();
  }
</script>
<style lang="less" scoped>
  .login {
    width: 100%;
    height: 100vh;
    background: url(@/assets/images/login-bg.png) no-repeat center;
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;

    .login-card {
      min-width: 460px;
      height: 600px;
      // [水平偏移] [垂直偏移] [模糊半径] [扩散半径] [颜色];
      box-shadow: 3px 5px 10px rgba(0, 0, 0, 0.1);

      .captcha-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        vertical-align: middle;
        .captcha-img {
          height: 40px;
          display: inline-block;
        }
      }

      .submit {
        width: 100%;
      }
    }
  }
</style>
